package cn.ac.iie.di.ban.ycl.cleaner.handler;

import cn.ac.iie.di.datadock.rdata.exchange.client.v1.REMessage;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张明诚
 * @date 2016-12-4 14:35:51
 * @version V1.0
 * @desc
 */
public class CtTimeDataCountEveryDay {

    //按照微信发布时间（nc）统计数据
    public Map<String, Integer> getcTTimeDataCount(REMessage message) throws Exception {
        //key：ct  value：次数
        Map<String, Integer> countMap = new HashMap<>();
        String[] columns = message.colNames;
        List<String> columnArr = Arrays.asList(columns);
        int columnIndex = columnArr.indexOf("ct");
        if (columnIndex < 0) {
            throw new Exception("nc field column does not exists!");
        }

        List<Object[]> datas = message.data;
        String ncTimeStr;
        for (Object[] data : datas) {
            ncTimeStr = getDay(data[columnIndex].toString());
            if (ncTimeStr != null && !ncTimeStr.isEmpty()) {
                addNcTimeDataCount(ncTimeStr, countMap);
            }
        }
        return countMap;
    }

    private void addNcTimeDataCount(String ncTimeStr, Map<String, Integer> countMap) {
        Integer count = countMap.get(ncTimeStr);
        if (count == null || 0 == count) {
            countMap.put(ncTimeStr, 1);
        } else {
            countMap.put(ncTimeStr, count + 1);
        }
    }

    private String getDay(String timestamp) {
        timestamp = timestamp + "000";
        Date date = new Date(Long.valueOf(timestamp));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String format = sdf.format(date);
        return format;
    }
}
